// Hardhat 部署脚本 - 讨饭合约
// deploy-begging.js

const hre = require("hardhat");

async function main() {
    console.log("🍚 开始部署讨饭合约...");

    // 获取部署者账户
    const [deployer] = await hre.ethers.getSigners();
    console.log("部署者地址:", deployer.address);

    // 检查余额
    const balance = await deployer.getBalance();
    console.log("部署者余额:", hre.ethers.utils.formatEther(balance), "ETH");

    // 部署参数
    const beggingReason = "急需生活费，求好心人帮助 🙏";
    const targetAmount = hre.ethers.utils.parseEther("1.0"); // 目标 1 ETH
    const minimumDonation = hre.ethers.utils.parseEther("0.001"); // 最低 0.001 ETH
    const durationInDays = 30; // 30天

    console.log("\n📋 部署参数:");
    console.log("讨饭原因:", beggingReason);
    console.log("目标金额:", hre.ethers.utils.formatEther(targetAmount), "ETH");
    console.log("最低捐赠:", hre.ethers.utils.formatEther(minimumDonation), "ETH");
    console.log("持续时间:", durationInDays, "天");

    try {
        // 1. 部署完整版讨饭合约
        console.log("\n🚀 部署 BeggingContract (完整版)...");
        const BeggingContract = await hre.ethers.getContractFactory("BeggingContract");
        const beggingContract = await BeggingContract.deploy(
            beggingReason,
            targetAmount,
            minimumDonation,
            durationInDays
        );
        await beggingContract.deployed();
        console.log("✅ BeggingContract 部署完成:");
        console.log("   地址:", beggingContract.address);
        console.log("   交易哈希:", beggingContract.deployTransaction.hash);

        // 2. 部署简化版讨饭合约
        console.log("\n🚀 部署 SimpleBeggingContract (简化版)...");
        const SimpleBeggingContract = await hre.ethers.getContractFactory("SimpleBeggingContract");
        const simpleBeggingContract = await SimpleBeggingContract.deploy();
        await simpleBeggingContract.deployed();
        console.log("✅ SimpleBeggingContract 部署完成:");
        console.log("   地址:", simpleBeggingContract.address);
        console.log("   交易哈希:", simpleBeggingContract.deployTransaction.hash);

        // 3. 部署时间限制版讨饭合约
        console.log("\n🚀 部署 TimeLimitedBegging (时间限制版)...");
        const TimeLimitedBegging = await hre.ethers.getContractFactory("TimeLimitedBegging");
        const timeLimitedBegging = await TimeLimitedBegging.deploy(
            beggingReason,
            targetAmount,
            24 // 24小时
        );
        await timeLimitedBegging.deployed();
        console.log("✅ TimeLimitedBegging 部署完成:");
        console.log("   地址:", timeLimitedBegging.address);
        console.log("   交易哈希:", timeLimitedBegging.deployTransaction.hash);

        // 等待确认
        console.log("\n⏳ 等待区块确认...");
        await beggingContract.deployTransaction.wait(2);
        await simpleBeggingContract.deployTransaction.wait(2);
        await timeLimitedBegging.deployTransaction.wait(2);

        // 验证部署
        console.log("\n🔍 验证合约部署...");

        // 验证完整版合约
        const contractOwner = await beggingContract.owner();
        const contractReason = await beggingContract.beggingReason();
        const contractTarget = await beggingContract.targetAmount();
        console.log("BeggingContract 验证:");
        console.log("  所有者:", contractOwner);
        console.log("  讨饭原因:", contractReason);
        console.log("  目标金额:", hre.ethers.utils.formatEther(contractTarget), "ETH");

        // 验证简化版合约
        const simpleOwner = await simpleBeggingContract.owner();
        console.log("SimpleBeggingContract 验证:");
        console.log("  所有者:", simpleOwner);

        // 验证时间限制版合约
        const timeOwner = await timeLimitedBegging.owner();
        const timeReason = await timeLimitedBegging.reason();
        const timeTarget = await timeLimitedBegging.targetAmount();
        console.log("TimeLimitedBegging 验证:");
        console.log("  所有者:", timeOwner);
        console.log("  讨饭原因:", timeReason);
        console.log("  目标金额:", hre.ethers.utils.formatEther(timeTarget), "ETH");

        // 输出部署摘要
        console.log("\n" + "=".repeat(60));
        console.log("🎉 部署完成! 合约地址摘要:");
        console.log("=".repeat(60));
        console.log("BeggingContract (完整版):");
        console.log(`  ${beggingContract.address}`);
        console.log("SimpleBeggingContract (简化版):");
        console.log(`  ${simpleBeggingContract.address}`);
        console.log("TimeLimitedBegging (时间限制版):");
        console.log(`  ${timeLimitedBegging.address}`);
        console.log("=".repeat(60));

        // 输出测试指令
        console.log("\n📝 测试指令:");
        console.log("1. 在 Remix 中导入合约地址");
        console.log("2. 使用 MetaMask 连接到 Sepolia 测试网");
        console.log("3. 调用 donate() 函数进行捐赠测试");
        console.log("4. 调用 getDonation(address) 查询捐赠金额");
        console.log("5. 调用 withdraw() 提取资金 (仅所有者)");

        // 在区块链浏览器中查看
        console.log("\n🔗 区块链浏览器链接:");
        console.log(`BeggingContract: https://sepolia.etherscan.io/address/${beggingContract.address}`);
        console.log(`SimpleBeggingContract: https://sepolia.etherscan.io/address/${simpleBeggingContract.address}`);
        console.log(`TimeLimitedBegging: https://sepolia.etherscan.io/address/${timeLimitedBegging.address}`);

        // 保存部署信息到文件
        const deploymentInfo = {
            timestamp: new Date().toISOString(),
            network: hre.network.name,
            deployer: deployer.address,
            contracts: {
                BeggingContract: {
                    address: beggingContract.address,
                    txHash: beggingContract.deployTransaction.hash,
                    parameters: {
                        reason: beggingReason,
                        targetAmount: targetAmount.toString(),
                        minimumDonation: minimumDonation.toString(),
                        durationInDays: durationInDays
                    }
                },
                SimpleBeggingContract: {
                    address: simpleBeggingContract.address,
                    txHash: simpleBeggingContract.deployTransaction.hash
                },
                TimeLimitedBegging: {
                    address: timeLimitedBegging.address,
                    txHash: timeLimitedBegging.deployTransaction.hash,
                    parameters: {
                        reason: beggingReason,
                        targetAmount: targetAmount.toString(),
                        durationInHours: 24
                    }
                }
            }
        };

        // 写入部署信息文件
        const fs = require('fs');
        const path = require('path');
        const deploymentPath = path.join(__dirname, 'deployment-info.json');
        fs.writeFileSync(deploymentPath, JSON.stringify(deploymentInfo, null, 2));
        console.log(`\n💾 部署信息已保存到: ${deploymentPath}`);

    } catch (error) {
        console.error("\n❌ 部署失败:", error);
        process.exit(1);
    }
}

// 错误处理
main().catch((error) => {
    console.error("\n💥 脚本执行出错:", error);
    process.exitCode = 1;
});
